package com.sun.springbootfiledownload.controller;

import com.sun.springbootfiledownload.result.AliyunOssResult;
import com.sun.springbootfiledownload.service.FileAsyncService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * @version 1.0
 * @Package: com.sun.springbootfiledownload.controller
 * @ClassName: AsyncAliyunOSSController
 * @Author: sgq
 * @Date: 2025/4/10 14:33
 * @Description: TODD
 */
@Slf4j
@RestController
@RequestMapping("/api/async/oss")
public class AsyncAliyunOSSController {

    @Autowired
    private FileAsyncService fileAsyncService;

    /**
     * 异步上传文件到OSS
     *
     * @param file   上传的文件
     * @param folder 上传到的文件夹
     * @return 上传任务ID
     */
    @PostMapping("/upload")
    public String asyncUploadToOSS(@RequestParam("file") MultipartFile file,
                                   @RequestParam(value = "folder", defaultValue = "default") String folder) {
        CompletableFuture<AliyunOssResult> future = fileAsyncService.asyncUpload(file, folder);
        // 在实际应用中，可以返回任务ID供客户端查询状态
        return "文件上传任务已提交，文件名: " + file.getOriginalFilename();
    }

    @PostMapping("/super-safe")
    public ResponseEntity<?> superSafeUpload(@RequestParam("file") MultipartFile file,
                                             @RequestParam(value = "folder", defaultValue = "default") String folder
    ) {
        try {
            CompletableFuture<String> future = fileAsyncService.absolutelySafeUpload(file, folder);

            // 返回接受状态，不阻塞等待任务完成
            return ResponseEntity.accepted().body(Map.of(
                    "status", "processing",
                    "trackingId", "pending" // 实际项目中应返回任务ID
            ));
        } catch (Exception e) {
            return ResponseEntity.badRequest().body(Map.of(
                    "error", "请求处理失败",
                    "reason", e.getMessage()
            ));
        }
    }

    /**
     * 异步从OSS下载文件
     *
     * @param filePath OSS中的文件路径
     * @return 文件响应实体
     */
    @GetMapping("/download")
    public ResponseEntity<byte[]> asyncDownloadFromOSS(@RequestParam String filePath)
            throws ExecutionException, InterruptedException {
        CompletableFuture<byte[]> future = fileAsyncService.asyncDownload(filePath);

        // 等待异步任务完成
        byte[] fileContent = future.get();

        // 从文件路径中提取文件名
        String fileName = filePath.substring(filePath.lastIndexOf("/") + 1);

        // 设置响应头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", fileName);

        return ResponseEntity.ok()
                .headers(headers)
                .body(fileContent);
    }
}
